#include "thread_poll.h"

ThreadPoll::ThreadPoll(int threads, int taskCapacity)
:threads_(threads), taskCapacity_(taskCapacity), isRunning_(true), tasks_(taskCapacity)
{
    for(int i{}; i < threads; i++){
        poll_.emplace_back( thread(&ThreadPoll::run_, this) );
    }

    cout << "thread poll init success\n";
}

ThreadPoll::~ThreadPoll()
{
    isRunning_ = false;
    tasks_.wakeup();

    for(auto &thread: poll_){
        if(thread.joinable())
            thread.join();
    }
}

void ThreadPoll::run_()
{
    while(isRunning_){
        Task *task = tasks_.getTask();
        if(!task)
            continue;

        task->work();

        if(task)
            delete task;
    }
}

int ThreadPoll::addTask(Task *task)
{
    return tasks_.addTask(task);
}